Adding search to a Rails app.
I wanted to add search to my Rails application. Here’s what I did.
1. Search code to the controller, this controller was already built using a scaffold around a Table called “Words”:
controllers/words_controller.rb:
1 2 3 4 5 6 7 8 | def search @words = Word.where( "word = ?" ,params[ :id ]) #all #find(params[:id]) respond_to do |format| format.html # search.html.erb format.json { render json: @words } end end |
I added a view based around the index.html.erb already present. It’s basically identical:
app/views/words/search.html.erb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | < h1 >Search results</ h1 > < table > < tr > < th >Word</ th > < th >Definition</ th > < th >Tags</ th > < th ></ th > < th ></ th > < th ></ th > </ tr > <% @words.each do |word| %> < tr > < td ><%= word.word %></ td > < td ><%= word.tags %></ td > < td ><%= word.definition %></ td > < td ><%= link_to 'Show', word %></ td > < td ><%= link_to 'Edit', edit_word_path(word) %></ td > < td ><%= link_to 'Destroy', word, confirm: 'Are you sure?', method: :delete %></ td > </ tr > <% end %> </ table > < br /> <%= link_to 'New Word', new_word_path %> <% if session[:user_id] %> <%= button_to 'Logout', logout_path, method: :delete %> <% end %> </ div > < div id = "main" > <%= yield %> |
I added the following rule to config/routes.rb:
1 | match ':controller(/:action(/:id))' |
Which if I’ve understood it correctly sends any http://blah/anycontroller/action/something to the anycontroller’s action method using something as a parameter (kind of).
I can then do searches such as:
http://localhost:3000/words/search/wordtosearchfor
Notes
Will need to add a html form to perform the search (somehow).
Clearly not great if you’re code is returning a lot of search results.
[…] first attempt is here. However that lacked a search box. It was neat in that you could reference the search directly as […]